export class BaseInput {
    constructor(form, dom){
        this.form = form;
        this.app = form.app;
        this.api = form.app.api;
        this.dom = dom;

        this._label = '';
        this._allowEmpty = false;
        this._hasValidation = false;

        this.prepareValidation();
        this.dom.on('input', this._onInput.bind(this));
    }

    prepareValidation(){
        this._validationMsg = this.dom.parent('div').append('<div class="px-4 validation" style="display: none;"></div>').find('.validation');
    }

    validate(){
        if(!this._allowEmpty && this.dom.val().length == 0){
            this.setValidation(false, '请填写' + this._label);
            return false;
        } else {
            return true;
        }
    }

    //设置验证状态显示
    setValidation(isValid, message = ''){
        this._hasValidation = true;
        if(isValid){
            this.dom.removeClass('is-invalid').addClass('is-valid');
            this._validationMsg.show().removeClass('invalid-feedback').addClass('valid-feedback').text(message);
        } else {
            this.dom.removeClass('is-valid').addClass('is-invalid');
            this._validationMsg.show().removeClass('valid-feedback').addClass('invalid-feedback').text(message);
        }
    }

    unsetValidation(){
        this.dom.removeClass(['is-valid', 'is-invalid']);
        this._validationMsg.removeClass(['valid-feedback', 'invalid-feedback']).hide();
        this._hasValidation = false;
    }

    _onInput(){
        if(this._hasValidation){
            this.unsetValidation();
        }
    }

    getValue(){
        return this.dom.val();
    }
}